using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace CGF
{
    public class CreateComponent
    {
        [MenuItem("CGFramework/创建 Component #Z", priority = -1200)]
        static void Create()
        {
            string defaultPath = $"{Application.dataPath}/{Define.DevelopScriptDir}";
            string path = EditorUtility.SaveFilePanel("创建组件", defaultPath, "", "cs");
            if (string.IsNullOrEmpty(path))
            {
                return;
            }
            if (path.Contains("Scripts_Main"))
            {
                if (EditorUtility.DisplayDialog("提示", "只能选择 Scripts_Hotfix 目录", "确定"))
                {
                    Create();
                }
                return;
            }
            if (path.Contains("Scripts_Hotfix/CGFramework"))
            {
                if (EditorUtility.DisplayDialog("提示", "不能选择 CGFramework 目录", "确定"))
                {
                    Create();
                }
                return;
            }
            if (File.Exists(path))
            {
                if (EditorUtility.DisplayDialog("提示", "该组件已存在\n\n请定义个新的组件名称", "确定"))
                {
                    Create();
                }
                return;
            }

            CreateFiles(path);
        }

        private static bool CreateFiles(string outputFullPath)
        {
            string templatePath = $"{Application.dataPath}/{Define.ScriptsHotfixFolder}/CGFramework/Editor/CreateComponent/Templates//Component.cs.txt";
            //创建组件类
            string componentTemplate = File.ReadAllText(templatePath);
            string componentClassName = Path.GetFileNameWithoutExtension(outputFullPath);
            string componentCode = componentTemplate.Replace("#ClassName#", componentClassName);
            if (!File.Exists(outputFullPath)) SaveFile(outputFullPath, componentCode);
            AssetDatabase.ImportAsset(outputFullPath.Replace(Application.dataPath, "Assets"));
            return true;
        }

        private static void SaveFile(string path, string content)
        {
            string folder = Path.GetDirectoryName(path);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            File.WriteAllText(path, content, new UTF8Encoding(false));
        }

    }
}